# -*- coding: utf-8 -*-

import time
from odoo import api, models, _

from datetime import datetime
from dateutil.relativedelta import relativedelta
from collections import OrderedDict


class ReportPartnerLedger(models.AbstractModel):
    _inherit = 'report.accounting_pdf_reports.report_partnerledger'

    @api.model
    def _get_report_values2(self, docids, data=None):
        res = self._get_report_values(docids, data)

        partners = []
        fn_sum = res.get('sum_partner')
        fn_lines = res.get('lines')
        for ptn in res['docs']:
            partner_data = {}
            partner_data['id'] = ptn.id
            partner_data['partner_id'] = ptn.id
            partner_data['partner_name'] = ptn.name
            partner_data['partner_display_name'] = ptn.display_name
            partner_data['debit'] = fn_sum(res['data'], ptn, 'debit')
            partner_data['credit'] = fn_sum(res['data'], ptn, 'credit')
            partner_data['balance'] = fn_sum(
                res['data'], ptn, 'debit - credit')
            partner_data['lines'] = fn_lines(res['data'], ptn)
            partners = partners + [partner_data]

        res['report_data'] = partners

        return res


class AccountPartnerLedger(models.TransientModel):
    _inherit = "account.report.partner.ledger"

    @api.model
    def report_print(self, values, callback):
        # callback( values )
        # print('-----report_print, value,', values)

        date_from = values.get('date_from')
        date_to_init = datetime.strptime(
            date_from, '%Y-%m-%d') + relativedelta(days=-1)
        date_to_init = date_to_init.strftime('%Y-%m-%d')

        values_init = values.copy()
        values_init.update({'date_from': False, 'date_to': date_to_init})
        res_init = callback(values_init)

        values_end = values.copy()
        values_end.update({'date_from': False})
        res_end = callback(values_end)
        res = callback(values, )

        # print('-----report_print, res_init,', res_init)
        # print('-----report_print, res_end,', res_end)

        def fn1(rec, date_from):
            rec2 = rec.copy()
            del rec2['lines']
            rec2['lines'] = [{
                # id = 0 这个是标志
                'id': 0, 'date': date_from, 'code': '', 'a_code': '', 'a_name': '', 'ref': None,
                # name 可以用来显示
                'move_name': 'Initial Balance', 'name': 'Initial Balance',
                # 赋值 debit, credit
                'debit': rec['debit'], 'credit': rec['credit'],
                'amount_currency': 0.0,
                'currency_id': 'res.currency()', 'currency_code': None,
                # name 可以用来显示
                'displayed_name': 'Initial Balance',
                # 赋值 progress
                'progress': rec['balance']
            }]
            return rec2

        def fn2(rec, date_from):
            rec2 = rec.copy()
            del rec2['lines']
            lines = [ln for ln in rec['lines'] if ln['date']
                     >= datetime.strptime(date_from, '%Y-%m-%d').date()]
            rec2['lines'] = lines
            return rec2

        rpt_init = [fn1(rec, date_from) for rec in res_init['report_data']]
        rpt_end = [fn2(rec, date_from) for rec in res_end['report_data']]

        res['report_data'] = merge_report_data(rpt_init, rpt_end)

        # print('-----report_print, res,', res)

        return res


def merge_report_data(res1, res2):
    d = OrderedDict()
    for r in res1:
        d[r['id']] = r

    for r in res2:
        rid = r['id']
        if rid not in d:
            d[rid] = r
            continue

        nr = r.copy()
        nr['lines'] = d[rid]['lines'] + r['lines']
        d[rid] = nr

    return list(d.values())
